package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.lili.cache.impl.RedisCache;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.BeanUtil;
import cn.lili.common.utils.DateUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.entity.enums.DistributionStatusEnum;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.order.entity.dos.*;
import cn.lili.modules.order.order.entity.dto.RankingActivityConfigDTO;
import cn.lili.modules.order.order.entity.dto.TopUserDTO;
import cn.lili.modules.order.order.entity.vo.*;
import cn.lili.modules.order.order.mapper.RankingActivityConfigMapper;
import cn.lili.modules.order.order.service.*;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.dos.Dictionary;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 活动配置列表 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RankingActivityConfigServiceImpl extends ServiceImpl<RankingActivityConfigMapper, RankingActivityConfig> implements IRankingActivityConfigService {

    private final IRankingAwardsService rankingAwardsService;

    private final IRankingScoreDetailsService rankingScoreDetailsService;

    private final UserClient userClient;

    private final DictionaryClient dictionaryClient;

    private final IRankingAwardDetailsService rankingAwardDetailsService;

    private final IRankingGrowAwardStatusService growAwardStatusService;

    private final IRankingDistributionService distributionService;

    private final DistributionClient distributionClient;

    private final RedisCache redisCache;
    /**
     * 当前活动id
     */
    private static final String CURRENT_RANKING_ACTIVITY_ID = "current_ranking_activity_id:";

    /**
     * 活动列表
     *
     * @return
     */
    @Override
    public Page<RankingActivityConfigVO> getRankingActivityConfig(RankingActivityConfigDTO dto) {
        if (null == dto.getStartDate()) {
            dto.setStartDate(null);
        }
        if (null == dto.getEndDate()) {
            dto.setEndDate(null);
        }
        if (null != dto.getStartDate() && null != dto.getEndDate()) {
            dto.setStartDate(dto.getStartDate() + " 00:00:00");
            dto.setEndDate(dto.getEndDate() + " 23:59:59");
        }
        //查找活动列表
        Page<RankingActivityConfigVO> page = baseMapper.getRankingActivityConfig(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto);
        log.info("JSONObject == {}" + JSONObject.toJSONString(page.getRecords()));
        //不显示当前活活在列表里
        if (CollUtil.isNotEmpty(page.getRecords())) {
            String currentId = "";
            Object currentIdRedisObj = redisCache.get(CURRENT_RANKING_ACTIVITY_ID);
            if (null == currentIdRedisObj || StringUtils.isEmpty(currentIdRedisObj.toString())) {
                RankingActivityConfigVO currentVo = this.getCurrentRankingActivity();
                if (null != currentVo) {
                    currentId = currentVo.getId();
                }
            } else {
                currentId = currentIdRedisObj.toString();
            }
            if (StringUtils.isNotEmpty(currentId)) {
                for (int i = 0; i < page.getRecords().size(); i++) {
                    if (page.getRecords().get(i).getId().equals(currentId)) {
                        page.getRecords().remove(i);
                    }
                }
            }
            if (CollUtil.isNotEmpty(page.getRecords())) {
                //活动id
                List<String> configIds = page.getRecords().stream().map(RankingActivityConfigVO::getId).collect(Collectors.toList());
                //查询总积分
                List<RankingActivityConfigVO> peopleNumsList = baseMapper.selectActivitypeopleNumByActivityIds(configIds);
                //查询总积分
                List<RankingActivityConfigVO> totalScoresList = baseMapper.selectActivitytotalScoreByActivityIds(configIds);
                //参与人数
                if (CollUtil.isNotEmpty(peopleNumsList)) {
                    //转map
                    Map<String, RankingActivityConfigVO> map = peopleNumsList.stream().collect(Collectors.toMap(RankingActivityConfigVO::getId, rankingActivityConfigVO -> rankingActivityConfigVO));
                    for (RankingActivityConfigVO vo : page.getRecords()) {
                        if (map.containsKey(vo.getId())) {
                            //TODO 如果这里需要判断佣金条件,则在这里判断
                            vo.setPeopleNum(map.get(vo.getId()).getPeopleNum());
                        }
                    }
                }
                //总积分
                if (CollUtil.isNotEmpty(totalScoresList)) {
                    //转map
                    Map<String, RankingActivityConfigVO> scoreMap = totalScoresList.stream().collect(Collectors.toMap(RankingActivityConfigVO::getId, rankingActivityConfigVO -> rankingActivityConfigVO));
                    for (RankingActivityConfigVO vo : page.getRecords()) {
                        if (scoreMap.containsKey(vo.getId())) {
                            //TODO 如果这里需要判断佣金条件,则在这里判断
                            vo.setTotalScore(scoreMap.get(vo.getId()).getTotalScore());
                        }
                    }
                }

                QueryWrapper<RankingAwards> wrapper = new QueryWrapper<>();
                wrapper.in("activity_config_id", configIds);
                wrapper.eq("delete_flag", Boolean.FALSE);
                List<RankingAwards> rankingAwards = rankingAwardsService.list(wrapper);
                if (CollUtil.isNotEmpty(rankingAwards)) {
                    for (RankingActivityConfigVO configVo : page.getRecords()) {
                        for (RankingAwards rankAward : rankingAwards) {
                            if (configVo.getId().equals(rankAward.getActivityConfigId())) {
                                configVo.getRankingAwards().add(rankAward);
                            }
                        }
                    }
                }
            }
            return page;
        }
        return new Page<>();
    }

    /**
     * 查询当前活动
     *
     * @return
     */
    private RankingActivityConfigVO getCurrentRankingActivity() {
        RankingActivityConfigVO vo = baseMapper.getCurrentRankingActivityConfig(0);
        if (null == vo) {
            vo = baseMapper.getCurrentRankingActivityConfig(1);
        }
//        if (null == vo) {
//            vo = baseMapper.getCurrentRankingActivityConfig(2);
//        }
        if (null != vo) {
            long expired = (vo.getEndDate().getTime() - new Date().getTime()) < 120000 && (vo.getEndDate().getTime() - new Date().getTime()) > 0 ? vo.getEndDate().getTime() - new Date().getTime() : 120000;
            redisCache.put(CURRENT_RANKING_ACTIVITY_ID, vo.getId(), expired, TimeUnit.MILLISECONDS);
        }
        return vo;
    }


    /**
     * 当期活动
     *
     * @return
     */
    @Override
    public RankingActivityConfigVO getCurrentRankingActivityConfig() {
        //获取当前活动
        RankingActivityConfigVO vo = this.getCurrentRankingActivity();
        if (null != vo) {
            Date date = new Date();
            //活动状态
            if (vo.getStartDate().after(date)) {
                //未开始vv
                vo.setActivityStatus(0);
            } else if (vo.getStartDate().before(date) && vo.getEndDate().after(date) && vo.getActivityStatus() != 2) {
                vo.setActivityStatus(1);
            } else {
                vo.setActivityStatus(2);
            }

            QueryWrapper<RankingAwards> wrapper = new QueryWrapper<>();
            wrapper.eq("activity_config_id", vo.getId());
            wrapper.eq("delete_flag", Boolean.FALSE);
            List<RankingAwards> rankingAwards = rankingAwardsService.list(wrapper);
            if (CollUtil.isNotEmpty(rankingAwards)) {
                vo.setRankingAwards(rankingAwards);
            }
        }
        return vo;
    }

    /**
     * 检查是否有名次重复
     *
     * @param rankingAwards
     */
    @Override
    public void checkIsRepeatRankingNum(List<RankingAwards> rankingAwards) {
        //(新增,编辑排名活动)防止重复 名次条件 逻辑
        this.bubbleSort(rankingAwards);
        for (int i = 0; i < rankingAwards.size(); i++) {
            if (i >= 1 && (rankingAwards.get(i).getRankingMin() <= rankingAwards.get(i - 1).getRankingMin() ||
                    rankingAwards.get(i).getRankingMin() <= rankingAwards.get(i - 1).getRankingMax())) {
                throw new ServiceException("名次条件重复");
            }
        }
    }

    public static void bubbleSort(List<RankingAwards> list) {
        int n = list.size();
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (list.get(j).getRankingMin() > list.get(j + 1).getRankingMin()) {
                    // 交换位置
                    RankingAwards temp = list.get(j);
                    list.set(j, list.get(j + 1));
                    list.set(j + 1, temp);
                }
            }
        }
    }

    /**
     * 发布活动
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<Object> addRankingActivityConfig(RankingActivityConfigDTO dto) {
        this.checkParam(dto);
        //检查是否有名次重复
        this.checkIsRepeatRankingNum(dto.getRankingAwards());
        //检查是否有进行中的活动
        LambdaQueryWrapper<RankingActivityConfig> query = new LambdaQueryWrapper();
        query.eq(RankingActivityConfig::getDeleteFlag, Boolean.FALSE);
        Date date = new Date();
        query.le(RankingActivityConfig::getStartDate, date);
        query.ge(RankingActivityConfig::getEndDate, date);
        query.between(RankingActivityConfig::getActivityStatus, 0, 1);
        if (baseMapper.selectCount(query) > 0) {
            return ResultUtil.error(400, "有进行中的活动，请先结束活动");
        }
        //检测是否有重复日期的活动
        if (baseMapper.selectCountRepeatActivityDate(dto.getStartDate(), dto.getEndDate()) > 0) {
            return ResultUtil.error(400, "有重复日期的活动");
        }

        RankingActivityConfig config = new RankingActivityConfig();
        BeanUtil.copyProperties(dto, config);
        config.setStartDate(DateUtil.toDate(dto.getStartDate(), DateUtil.STANDARD_FORMAT));
        config.setEndDate(DateUtil.toDate(dto.getEndDate(), DateUtil.STANDARD_FORMAT));

        if (baseMapper.insert(config) > 0) {
            dto.getRankingAwards().stream().forEach(e -> e.setActivityConfigId(config.getId()));
            if (!rankingAwardsService.saveBatch(dto.getRankingAwards())) {
                throw new ServiceException("发布活动失败");
            }
        }
        return ResultUtil.success();
    }

    /**
     * 参数检查
     *
     * @param dto
     * @param
     * @return
     */
    private ResultMessage<Object> checkParam(RankingActivityConfigDTO dto) {
        if (StringUtils.isEmpty(dto.getActivityName())) {
            throw new ServiceException("活动名称不能为空");
        }
        if (null == dto.getStartDate() || null == dto.getEndDate()) {
            throw new ServiceException("活动日期不能为空");
        }
        Date date = new Date();
        if (DateUtil.toDate(dto.getStartDate(), DateUtil.STANDARD_FORMAT).before(DateUtil.startOfTodDayTime())) {
            throw new ServiceException("活动日期不能小于当前天");
        }
        if (DateUtil.toDate(dto.getStartDate(), DateUtil.STANDARD_DATE_FORMAT).getTime() == (DateUtil.toDate(dto.getEndDate(), DateUtil.STANDARD_DATE_FORMAT).getTime())) {
            throw new ServiceException("活动开始日期不可与结束日期是同一天");
        }
        if (CollUtil.isEmpty(dto.getRankingAwards())) {
            throw new ServiceException("奖品不能为空");
        }
        return ResultUtil.success();
    }


    /**
     * 更新活动
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<Object> editRankingActivityConfig(RankingActivityConfigDTO dto) {
        if (null == dto.getId()) {
            return ResultUtil.error(400, "id不能为空");
        }
        QueryWrapper<RankingActivityConfig> query = new QueryWrapper<>();
        query.lambda().eq(RankingActivityConfig::getId, dto.getId());
        RankingActivityConfig config = baseMapper.selectOne(query);
        if (null == config) {
            return ResultUtil.error(400, "未找到此活动");
        }

        if (dto.getActivityStatus() == null || dto.getActivityStatus() != 2 && null != config.getStartDate() && config.getStartDate().before(new Date())) {
            return ResultUtil.error(400, "活动已开始,不可修改");
        }
        RankingActivityConfig configParam = new RankingActivityConfig();
        BeanUtil.copyProperties(dto, configParam);
        //编辑更新日期
        if (StringUtils.isNotEmpty(dto.getStartDate()) && StringUtils.isNotEmpty(dto.getEndDate())) {
            configParam.setStartDate(DateUtil.toDate(dto.getStartDate(), DateUtil.STANDARD_FORMAT));
            configParam.setEndDate(DateUtil.toDate(dto.getEndDate(), DateUtil.STANDARD_FORMAT));
        }
        //结束活动,把结束时间更改为当前时间
        if (null != dto.getActivityStatus() && dto.getActivityStatus() == 2) {
            configParam.setEndDate(new Date());
        }
        int result = baseMapper.updateById(configParam);
        if (result > 0 && null != dto.getActivityStatus() && dto.getActivityStatus() == 2) {
            Object objId = redisCache.get(CURRENT_RANKING_ACTIVITY_ID);
            if (null != objId && objId.toString().equals(dto.getId())) {
                redisCache.remove(CURRENT_RANKING_ACTIVITY_ID);
            }
            return ResultUtil.success();
        }
        if (rankingAwardsService.updateBatchRankingAwards(dto.getRankingAwards(), configParam.getId()) > 0) {
            return ResultUtil.success();
        }
        throw new ServiceException("更新奖品失败");
    }


    /**
     * 删除活动
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> deleteRankingActivityConfig(RankingActivityConfigDTO dto) {
        Date date = new Date();
        RankingActivityConfig config = baseMapper.selectById(dto.getId());
        if (null == config || config.getDeleteFlag()) {
            return ResultUtil.error(400, "未找到此活动");
        }
        if (config.getStartDate().before(date) && config.getEndDate().after(date) && config.getActivityStatus() != 2) {
            return ResultUtil.error(400, "有进行中的活动，请先结束活动");
        }
        UpdateWrapper<RankingActivityConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", dto.getId());
        updateWrapper.set("delete_flag", Boolean.TRUE);
        if (this.update(updateWrapper)) {
            Object objId = redisCache.get(CURRENT_RANKING_ACTIVITY_ID);
            if (null != objId && objId.toString().equals(dto.getId())) {
                redisCache.remove(CURRENT_RANKING_ACTIVITY_ID);
            }
            return ResultUtil.success();
        } else {
            return ResultUtil.error();
        }

    }

    /**
     * 删除活动奖品
     *
     * @param rankingAwards
     * @return
     */
    @Override
    public ResultMessage<Object> deleteRankingActivityAward(RankingAwards rankingAwards) {
        if (StringUtils.isEmpty(rankingAwards.getId())) {
            return ResultUtil.error(400, "缺少核心参数");
        }
        //查询当前奖品是否存在
        LambdaQueryWrapper<RankingAwards> query = new LambdaQueryWrapper<>();
        query.eq(RankingAwards::getId, rankingAwards.getId());
        query.eq(RankingAwards::getDeleteFlag, Boolean.FALSE);
        RankingAwards rankingAwardsData = rankingAwardsService.getOne(query);
        if (rankingAwardsData == null) {
            return ResultUtil.error(400, "该奖品不存在");
        }

        //判断活动是否开始
        Date date = new Date();
        LambdaQueryWrapper<RankingActivityConfig> configQuery = new LambdaQueryWrapper<>();
        configQuery.le(RankingActivityConfig::getStartDate, date);
        configQuery.ge(RankingActivityConfig::getEndDate, date);
        if (baseMapper.selectCount(configQuery) > 0) {
            return ResultUtil.error(400, "活动正在进行中，不可删除");
        }

        rankingAwards.setDeleteFlag(true);
        if (rankingAwardsService.updateById(rankingAwards)) {
            return ResultUtil.success();
        }
        return ResultUtil.error(400, "删除失败");
    }

    /**
     * 获取当前排名活动
     */
    @Override
    public RankingActivityConfig getCurrentActivity() {
        Date date = new Date();
        LambdaQueryWrapper<RankingActivityConfig> configQuery = new LambdaQueryWrapper<>();
        configQuery.le(RankingActivityConfig::getStartDate, date);
        configQuery.ge(RankingActivityConfig::getEndDate, date);
        configQuery.ne(RankingActivityConfig::getActivityStatus, DictConstant.ACTIVITY_STATUS_02);
        configQuery.orderByDesc(RankingActivityConfig::getCreateTime);
        configQuery.last("limit 1");

        return super.getOne(configQuery);
    }

    /**
     * 获取当前，排名达到要求，且前三位店主的信息。 与 排名活动奖品
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultMessage<Object> getTopAwards() {
        TopAwardsVO result = new TopAwardsVO();
        result.setAwardsList(new ArrayList<>());
        result.setTopUserList(new ArrayList<>());
        result.setActivityId("");

        //活动配置
        RankingActivityConfig currentActivity = this.getCurrentActivity();
        if (currentActivity == null) {
            //当前无活动。返回未开始的活动
            LambdaQueryWrapper<RankingActivityConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.gt(RankingActivityConfig::getStartDate, LocalDateTime.now());
            queryWrapper.ne(RankingActivityConfig::getActivityStatus, DictConstant.ACTIVITY_STATUS_02);
            queryWrapper.orderByDesc(RankingActivityConfig::getCreateTime);
            queryWrapper.last("limit 1");
            currentActivity = super.getOne(queryWrapper);
            if (currentActivity == null) {
                //无未开始的，返回老数据
                queryWrapper.clear();
                queryWrapper.and(q -> q.le(RankingActivityConfig::getEndDate, LocalDateTime.now()).or().eq(RankingActivityConfig::getActivityStatus, DictConstant.ACTIVITY_STATUS_02));
                queryWrapper.orderByDesc(RankingActivityConfig::getCreateTime);
                queryWrapper.last("limit 1");
                currentActivity = super.getOne(queryWrapper);
                if (currentActivity == null) {
                    return ResultUtil.data(result);
                }
            }
        }
        if (currentActivity.getCommissCondition() == null) {
            log.error("排名条件未配置 == {} ", JSONObject.toJSONString(currentActivity));
            throw new ServiceException("排名条件未配置");
        }
        //添加返回数据
        this.addResult(currentActivity, result);
        result.setActivityId(currentActivity.getId());

        //获取达到要求 且排名前三的用户
        List<TopUserDTO> topUserDTOS = rankingScoreDetailsService.topUser(currentActivity, currentActivity.getCommissCondition().doubleValue(), DictConstant.SCORE_ORDER_STATUS_02);
        if (CollectionUtil.isEmpty(topUserDTOS)) {
            log.error("该活动 【{}】 没有达到条件的用户", currentActivity.getId());
            return ResultUtil.data(result);
        }

        List<TopUserVO> userVOS = new ArrayList<>();
        if (topUserDTOS.size() > 3) {
            //只取前三条
            topUserDTOS = topUserDTOS.stream().limit(3).collect(Collectors.toList());
        }
        for (TopUserDTO topUserDTO : topUserDTOS) {
            User user = userClient.getById(topUserDTO.getUid());
            if (user == null || StringUtils.isEmpty(user.getId())) {
                log.error("根据 【{}】未获取到用户信息", JSONObject.toJSONString(topUserDTO));
                continue;
            }
            TopUserVO topUserVO = new TopUserVO();
            topUserVO.setUserId(user.getId());
            topUserVO.setUserImage(user.getFace());
            topUserVO.setUsername(StringUtils.isNotEmpty(user.getNickName()) ? user.getNickName() : user.getFyName());
            userVOS.add(topUserVO);
        }
        result.setTopUserList(userVOS);
        return ResultUtil.data(result);
    }

    /**
     * 添加返回数据
     */
    public void addResult(RankingActivityConfig currentActivity, TopAwardsVO result) {
        //获取前三的奖品
        List<RankingAwards> rankingAwardsList = rankingAwardsService.getAwardsByActivity(currentActivity.getId());
        if (CollectionUtil.isNotEmpty(rankingAwardsList)) {
            List<RankingAwards> collect = rankingAwardsList.stream().sorted(Comparator.comparing(RankingAwards::getRankingMin)).limit(3).toList();
            log.info("filter result == {} ", JSONObject.toJSONString(collect));
            result.setAwardsList(collect);
        }
        String start = DateUtil.toString(currentActivity.getStartDate(), "yyyy/MM/dd");
        String end = DateUtil.toString(currentActivity.getEndDate(), "yyyy/MM/dd");
        result.setAwardsTime(start + "-" + end);
    }

    /**
     * 活动详情
     *
     * @param id 活动id
     * @return 活动详情
     */
    @Override
    public ResultMessage<Object> activityDetail(String id) {
        RankingActivityConfig currentActivity = super.getById(id);
        if (currentActivity == null) {
            throw new ServiceException("未获取到，活动信息");
        }
        TopAwardsVO result = new TopAwardsVO();
        result.setAwardsList(new ArrayList<>());

        if (currentActivity.getCommissCondition() == null) {
            log.error("排名条件未配置 == {} ", JSONObject.toJSONString(currentActivity));
            throw new ServiceException("排名条件未配置");
        }
        //添加返回数据
        this.addResult(currentActivity, result);

        return ResultUtil.data(result);
    }

    /**
     * 小提示列表
     *
     * @param id 活动id
     * @return 小提示列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TipsVO tipsList(String id) {
        TipsVO tipsVO = new TipsVO();
        RankingDistribution rankingDistribution = distributionService.getRankingDistribution();
        // 设置默认值
        this.setDefault(tipsVO);

        // 查询当前活动是否已经开始
        RankingActivityConfig currentActivity = this.getCurrentActivity();
        if (currentActivity != null) {
            handleCurrentActivity(tipsVO, rankingDistribution, currentActivity);
            return tipsVO;
        }

        // 查询新建但还未开始的活动
        currentActivity = this.getUpcomingActivity(id);
        if (currentActivity != null) {
            this.processUpcomingActivity(tipsVO, rankingDistribution, currentActivity);
            return tipsVO;
        }

        // 处理已结束的活动
        currentActivity = this.getClosedActivity(id);
        if (currentActivity != null) {
            this.processClosedActivity(tipsVO, rankingDistribution, currentActivity);
            return tipsVO;
        }

        // 没有查询到相关活动
        this.handleNoActivity(tipsVO);
        return tipsVO;
    }

    /**
     * 设置默认值
     */
    private void setDefault(TipsVO tipsVO) {
        // 设置默认值
        tipsVO.setTips("");
        tipsVO.setIsPrize(false);
        tipsVO.setClosing(false);
        tipsVO.setIsStart(false);
        tipsVO.setCurrentRanking(-1);
        tipsVO.setScore(BigDecimal.valueOf(0));
        tipsVO.setIsStore(false);
        tipsVO.setStore(0);
        tipsVO.setRanking(false);
        //0不是店主，1是店主，2正在审核。3审核被驳回。
        Distribution distribution = distributionClient.getDistribution(UserContext.getCurrentId());
        if (distribution != null) {
            if (DistributionStatusEnum.APPLY.name().equals(distribution.getDistributionStatus())) {
                tipsVO.setStore(2);
            }
            if (DistributionStatusEnum.PASS.name().equals(distribution.getDistributionStatus())) {
                tipsVO.setStore(1);
                tipsVO.setIsStore(true);
            }
            if (DistributionStatusEnum.REFUSE.name().equals(distribution.getDistributionStatus())) {
                tipsVO.setStore(3);
            }
            tipsVO.setDistribution(distribution);
        }
        tipsVO.setCount(growAwardStatusService.countUser());
    }

    /**
     * 处理当前活动
     */
    private void handleCurrentActivity(TipsVO tipsVO, RankingDistribution rankingDistribution, RankingActivityConfig currentActivity) {
        // 设置活动开始标志为 true
        tipsVO.setIsStart(true);

        // 进行排名计算
        ranking(rankingDistribution, currentActivity, tipsVO);

        // 计算当前用户的积分
        currentScore(currentActivity, tipsVO);

        if (rankingDistribution == null) {
            // 如果排名数据为空，则设置提示信息为 "当前无排名数据"
            String noTips = getDictionaryValue(DictConstant.TIPS_03 + "");
            if (noTips != null) {
                String replace = noTips.replace("{X}", currentActivity.getCommissCondition().doubleValue() + "");
                tipsVO.setTips(replace);
            }
            return;
        }

        BigDecimal commissCondition = currentActivity.getCommissCondition();
        if (commissCondition.doubleValue() > rankingDistribution.getRebateTotal().doubleValue()) {
            // 如果当前用户的积分未达到门槛，则设置提示信息为 "还需要 {X} 积分才能进入排名"
            String noTips = getDictionaryValue(DictConstant.TIPS_03 + "");
            if (noTips != null) {
                String replace = noTips.replace("{X}", commissCondition.subtract(rankingDistribution.getRebateTotal()).doubleValue() + "");
                tipsVO.setTips(replace);
            }
            return;
        }

        // 获取排行榜前 N 名用户的信息
        List<TopUserDTO> topUserDTOList = rankingScoreDetailsService.topUser(currentActivity, commissCondition.doubleValue(), DictConstant.SCORE_ORDER_STATUS_02);
        Integer currentIndex = null;

        for (int i = 0; i < topUserDTOList.size(); i++) {
            TopUserDTO topUserDTO = topUserDTOList.get(i);
            if (topUserDTO.getUid().equals(UserContext.getCurrentId())) {
                currentIndex = i;
                break;
            }
        }

        if (currentIndex == null) {
            // 如果当前用户不在排行榜中，则设置提示信息为 "当前活动已开始，请获取积分，提升排名"
            tipsVO.setTips("当前活动已开始，请获取积分，提升排名");
            return;
        }

        // 设置当前用户的排名
        tipsVO.setCurrentRanking(currentIndex + 1);

        if (!currentIndex.equals(0)) {
            // 如果当前用户不是第一名，则设置提示信息为 "您当前排名第 {X} 名，距离上一名还差 {W} 积分"
            String noTips = getDictionaryValue(DictConstant.TIPS_04 + "");
            if (noTips != null) {
                String replaceStr = noTips.replace("{X}", currentIndex + 1 + "");
                TopUserDTO currentTopUser = topUserDTOList.get(currentIndex);
                TopUserDTO leftTopUserDTO = topUserDTOList.get(currentIndex - 1);
                replaceStr = replaceStr.replace("{W}", leftTopUserDTO.getSc().subtract(currentTopUser.getSc()).doubleValue() + "");
                tipsVO.setTips(replaceStr);
            }
            return;
        }

        // 如果当前用户是第一名，则设置提示信息为 "您当前排名第 1 名，距离下一名还差 {W} 积分"
        String noTips = getDictionaryValue(DictConstant.TIPS_05 + "");
        if (noTips != null) {
            TopUserDTO currentTopUser = topUserDTOList.get(currentIndex);
            TopUserDTO rightTopUserDTO = currentIndex != topUserDTOList.size() - 1 ? topUserDTOList.get(currentIndex + 1) : null;
            String replaceStr = noTips.replace("{X}", currentIndex + 1 + "");
            replaceStr = replaceStr.replace("{W}", currentTopUser.getSc().subtract(rightTopUserDTO != null ? rightTopUserDTO.getSc() : BigDecimal.valueOf(0)).doubleValue() + "");
            tipsVO.setTips(replaceStr);
        }
    }

    /**
     * 根据字典的 code、status 和 value 查询字典项，并返回其 valueName
     */
    private String getDictionaryValue(String value) {
        Dictionary dictionary = dictionaryClient.getDict(Dictionary.builder().code(DictConstant.TIPS_NO).status(DictConstant.STATUS_1).value(value).build());
        return dictionary != null ? dictionary.getValueName() : null;
    }

    /**
     * 查询新建但还未开始的活动
     */
    private RankingActivityConfig getUpcomingActivity(String id) {
        LambdaQueryWrapper<RankingActivityConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(RankingActivityConfig::getStartDate, LocalDateTime.now());
        queryWrapper.eq(RankingActivityConfig::getId, id);
        queryWrapper.ne(RankingActivityConfig::getActivityStatus, DictConstant.ACTIVITY_STATUS_02);
        queryWrapper.orderByDesc(RankingActivityConfig::getCreateTime);
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper);
    }

    /**
     * 处理新建但还未开始的活动
     */
    private void processUpcomingActivity(TipsVO tipsVO, RankingDistribution rankingDistribution, RankingActivityConfig currentActivity) {
        //是否入围排名
        this.ranking(rankingDistribution, currentActivity, tipsVO);
        //当前积分
        this.currentScore(currentActivity, tipsVO);
        //排名活动即将开始入选条件：业绩达到{X}，加油！
        Dictionary dictionary = dictionaryClient.getDict(Dictionary.builder().code(DictConstant.TIPS_NO).status(DictConstant.STATUS_1).value(DictConstant.TIPS_02 + "").build());
        if (dictionary != null) {
            String replace = dictionary.getValueName().replace("{X}", currentActivity.getCommissCondition().doubleValue() + "");
            tipsVO.setTips(replace);
        }
    }

    /**
     * 查询已结束的活动
     */
    private RankingActivityConfig getClosedActivity(String id) {
        return super.getById(id);
    }

    /**
     * 处理已结束的活动
     */
    private void processClosedActivity(TipsVO tipsVO, RankingDistribution rankingDistribution, RankingActivityConfig currentActivity) {
        //是否入围排名
        this.ranking(rankingDistribution, currentActivity, tipsVO);
        //当前积分
        this.currentScore(currentActivity, tipsVO);
        //活动已到期
        tipsVO.setIsStart(true);
        tipsVO.setClosing(true);

        //是否可以领取奖品
        List<TopUserDTO> topUserDTOList = rankingScoreDetailsService.topUser(currentActivity, currentActivity.getCommissCondition().doubleValue(), DictConstant.SCORE_ORDER_STATUS_02);
        //获取当前用户在排名中的位置
        int currentIndex = IntStream.range(0, topUserDTOList.size()).filter(i -> topUserDTOList.get(i).getUid().equals(UserContext.getCurrentId())).findFirst().orElse(-1);
        if (currentIndex == -1) { //如果未入选排名
            tipsVO.setTips("活动已结束，您未入选排名");
            return;
        }
        tipsVO.setTips("活动已结束，您的排名是：" + (currentIndex + 1));
        tipsVO.setCurrentRanking(currentIndex + 1);

        List<RankingAwards> awardsByActivity = rankingAwardsService.getAwardsByActivity(currentActivity.getId());
        if (CollectionUtil.isNotEmpty(awardsByActivity)) {
            //当前排名，小于 最大可领奖人 （例如： 排名5，  可领奖人 1~3,4~6,7~9），则可领奖
            List<Integer> maxIndexList = awardsByActivity.stream().sorted(Comparator.comparing(RankingAwards::getRankingMax).reversed()).map(RankingAwards::getRankingMax).collect(Collectors.toList());
            Integer maxIndex = maxIndexList.get(0);
            int current = currentIndex + 1;
            if (current < maxIndex) { //如果当前排名小于最大可领奖人，则可领奖品
                tipsVO.setIsPrize(true);
                //查询是否已经领取过奖品
                LambdaQueryWrapper<RankingAwardDetails> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                detailsLambdaQueryWrapper.eq(RankingAwardDetails::getActivityId, currentActivity.getId());
                detailsLambdaQueryWrapper.eq(RankingAwardDetails::getUserId, UserContext.getCurrentId());
                if (rankingAwardDetailsService.count(detailsLambdaQueryWrapper) <= 0) {
                    this.createAwardDetail(currentActivity, awardsByActivity, current);
                } else {
                    detailsLambdaQueryWrapper.ne(RankingAwardDetails::getAwardStatus, DictConstant.AWARD_STATUS_0);
                    detailsLambdaQueryWrapper.last("limit 1");
                    RankingAwardDetails awardDetails = rankingAwardDetailsService.getOne(detailsLambdaQueryWrapper);
                    if (awardDetails != null) {
                        tipsVO.setId(awardDetails.getId());
                    }
                }
            }
        }
    }

    /**
     * 处理没有查询到相关活动的情况
     */
    private void handleNoActivity(TipsVO tipsVO) {
        tipsVO.setClosing(false);
        //敬请等待运营团队开启排名活动
        Dictionary dictionary = dictionaryClient.getDict(Dictionary.builder().code(DictConstant.TIPS_NO).status(DictConstant.STATUS_1).value(DictConstant.TIPS_01 + "").build());
        if (dictionary != null) {
            tipsVO.setTips(dictionary.getValueName());
        }
    }

    /**
     * 是否入围排名
     */
    public void ranking(RankingDistribution rankingDistribution, RankingActivityConfig currentActivity, TipsVO tipsVO) {
        if (rankingDistribution != null && currentActivity.getCommissCondition().doubleValue() < rankingDistribution.getRebateTotal().doubleValue()) {
            tipsVO.setRanking(true);
        }
    }

    /**
     * 当前活动积分
     */
    public void currentScore(RankingActivityConfig currentActivity, TipsVO tipsVO) {
        BigDecimal bigDecimal = rankingScoreDetailsService.currentScore(currentActivity);
        if (bigDecimal != null && bigDecimal.doubleValue() > 0D) {
            tipsVO.setScore(bigDecimal);
        }
    }

    /**
     * 排名列表
     */
    @Override
    public ResultMessage<Object> rankingList(String id) {
        RankingActivityConfig currentActivity = super.getById(id);
        if (currentActivity == null) {
            return ResultUtil.data(new ArrayList<>());
        }
        List<TopUserDTO> topUserDTOList = rankingScoreDetailsService.topUserLimit(currentActivity, currentActivity.getCommissCondition().doubleValue(), DictConstant.SCORE_ORDER_STATUS_02, 0, 20);
        if (CollectionUtil.isEmpty(topUserDTOList)) {
            return ResultUtil.data(new ArrayList<>());
        }
        List<String> uidList = topUserDTOList.stream().map(TopUserDTO::getUid).collect(Collectors.toList());
        List<User> userList = userClient.selectUserListByIds(uidList);
        if (CollectionUtil.isEmpty(userList)) {
            return ResultUtil.data(topUserDTOList);
        }

        for (TopUserDTO topUserDTO : topUserDTOList) {
            for (User user : userList) {
                if (user == null || StringUtils.isEmpty(user.getId())) {
                    continue;
                }
                if (user.getId().equals(topUserDTO.getUid())) {
                    topUserDTO.setUserImage(user.getFace());
                    topUserDTO.setUsername(StringUtils.isNotEmpty(user.getFyName()) ? user.getFyName() : user.getNickName());
                }
            }
        }
        return ResultUtil.data(topUserDTOList);
    }

    /**
     * 历史记录
     *
     * @return 历史记录列表
     */
    @Override
    public ResultMessage<Object> historyList() {
        LambdaQueryWrapper<RankingActivityConfig> activityConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        activityConfigLambdaQueryWrapper.le(RankingActivityConfig::getEndDate, new Date());
        List<RankingActivityConfig> list = super.list(activityConfigLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            for (RankingActivityConfig rankingActivityConfig : list) {
                String start = DateUtil.toString(rankingActivityConfig.getStartDate(), "yyyy/MM/dd");
                String end = DateUtil.toString(rankingActivityConfig.getEndDate(), "yyyy/MM/dd");
                rankingActivityConfig.setActivityName(rankingActivityConfig.getActivityName() + " " + start + "-" + end);
            }
        }
        return ResultUtil.data(list);
    }

    /**
     * 历史记录详情
     *
     * @param id 活动id
     * @return 详情
     */
    @Override
    public ResultMessage<Object> historyDetail(String id) {
        HistoryVO historyVO = new HistoryVO();
        historyVO.setAwardsList(new ArrayList<>());
        historyVO.setUserList(new ArrayList<>());
        historyVO.setSelected(false);

        RankingActivityConfig currentActivity = super.getById(id);

        //获取本期奖品
        LambdaQueryWrapper<RankingAwards> awardsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        awardsLambdaQueryWrapper.eq(RankingAwards::getActivityConfigId, id);
        List<RankingAwards> awardsList = rankingAwardsService.list(awardsLambdaQueryWrapper);
        if (CollectionUtil.isEmpty(awardsList)) {
            log.error("未获取到本期奖品 == {} ", id);
            throw new ServiceException("未获取到本期奖品");
        }
        historyVO.setAwardsList(awardsList);

        Integer rankingMax = awardsList.stream().max(Comparator.comparingInt(RankingAwards::getRankingMax)).get().getRankingMax();
        //获取本期入围排名，且到达了奖励领取条件的
        List<TopUserDTO> topUserDTOList = rankingScoreDetailsService.topUserLimit(currentActivity, currentActivity.getCommissCondition().doubleValue(), DictConstant.SCORE_ORDER_STATUS_02, 0, 20);
        if (CollectionUtil.isEmpty(topUserDTOList)) {
            //为空代表没有人到达了。领取奖品的条件
            return ResultUtil.data(historyVO);
        }

        //当前排名
        Integer currentIndex = null;
        for (int i = 0; i < topUserDTOList.size(); i++) {
            TopUserDTO topUserDTO = topUserDTOList.get(i);
            if (topUserDTO.getUid().equals(UserContext.getCurrentId())) {
                currentIndex = i;
                break;
            }
        }
        //不为空代表入围排名了
        if (currentIndex != null) {
            historyVO.setSelected(true);
            historyVO.setRanking(currentIndex + 1);
        }

        //当前排名，小于 最大可领奖人 （例如： 排名5，  可领奖人 1~3,4~6,7~9），则可领奖
        List<User> userList = userClient.selectUserListByIds(topUserDTOList.stream().map(TopUserDTO::getUid).collect(Collectors.toList()));
        for (int index = 0; index < topUserDTOList.size(); index++) {
            for (RankingAwards rankingAwards : awardsList) {
                Integer startRank = rankingAwards.getRankingMin();
                Integer endRank = rankingAwards.getRankingMax();
                //当前排名
                int currenIndex = index + 1;
                // 判断当前排名是否在奖励规则范围内
                if (currenIndex >= startRank && currenIndex <= endRank) {
                    //可以领取奖品
                    TopUserDTO topUserDTO = topUserDTOList.get(index);
                    for (User user : userList) {
                        if (topUserDTO.getUid().equals(user.getId())) {
                            topUserDTO.setUsername(StringUtils.isNotEmpty(user.getNickName()) ? user.getNickName() : user.getFyName());
                            topUserDTO.setUserImage(user.getFace());
                        }
                    }
                    topUserDTO.setAwardsId(rankingAwards.getId());
                    topUserDTO.setAwardsName(rankingAwards.getAwardName());
                    topUserDTO.setAwardLevel(String.valueOf(rankingAwards.getAwardLevel()));
                }
            }
        }
        historyVO.setUserList(topUserDTOList);
        return ResultUtil.data(historyVO);
    }

    /**
     * 创建待领奖信息  ??? 当没有调用这个地方的可能会出现没有初始化
     */
    public void createAwardDetail(RankingActivityConfig currentActivity, List<RankingAwards> awardsByActivity, Integer currentIndex) {
        //当前排名领取的奖品
        RankingAwards currentAwards = null;
        if (CollectionUtil.isNotEmpty(awardsByActivity)) {
            //当前排名，小于 最大可领奖人 （例如： 排名5，  可领奖人 1~3,4~6,7~9），则可领奖
            for (RankingAwards rankingAwards : awardsByActivity) {
                Integer startRank = rankingAwards.getRankingMin();
                Integer endRank = rankingAwards.getRankingMax();
                // 判断当前排名是否在奖励规则范围内
                if (currentIndex >= startRank && currentIndex <= endRank) {
                    //可以领取奖品
                    currentAwards = rankingAwards;
                    break;
                }
            }
        }
        if (currentAwards == null) {
            log.error("未获取到，当前可领奖的奖品信息 {} == {}", JSONObject.toJSONString(awardsByActivity), currentIndex);
            return;
        }

        //查询当前用户是否能入围排名
        LambdaQueryWrapper<RankingScoreDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingScoreDetails::getCurrentActivityId, currentActivity.getId());
        queryWrapper.eq(RankingScoreDetails::getParentUserId, UserContext.getCurrentId());
        queryWrapper.ne(RankingScoreDetails::getOrderStatus, DictConstant.SCORE_ORDER_STATUS_03);
        queryWrapper.ge(RankingScoreDetails::getCreateTime, currentActivity.getStartDate());
        queryWrapper.le(RankingScoreDetails::getCreateTime, currentActivity.getEndDate());
        List<RankingScoreDetails> detailsList = rankingScoreDetailsService.list(queryWrapper);
        double unSettleCommiss = detailsList.stream().filter(f -> DictConstant.SCORE_ORDER_STATUS_01.equals(f.getOrderStatus())).map(RankingScoreDetails::getScore).map(BigDecimal::doubleValue).mapToDouble(Double::valueOf).sum();
        double settleCommiss = detailsList.stream().filter(f -> DictConstant.SCORE_ORDER_STATUS_02.equals(f.getOrderStatus())).map(RankingScoreDetails::getScore).map(BigDecimal::doubleValue).mapToDouble(Double::valueOf).sum();

        AuthUser authUser = UserContext.getCurrentUser();
        RankingAwardDetails rankingAwardDetails = RankingAwardDetails.builder()
                .activityId(currentActivity.getId())
                .userId(authUser.getId())
                .nickName(authUser.getNickName())
                .totalScore(BigDecimal.valueOf(settleCommiss).add(BigDecimal.valueOf(unSettleCommiss)))
                .settleCommiss(BigDecimal.valueOf(settleCommiss))
                .unSettleCommiss(BigDecimal.valueOf(unSettleCommiss))
                .rankingAwardId(currentAwards.getId())
                .awardName(currentAwards.getAwardName())
                .awardStatus(DictConstant.AWARD_STATUS_0)
                .build();
        rankingAwardDetailsService.save(rankingAwardDetails);
    }
}
